using System;
using Autofac;

namespace Codeflows.Contrib.Autofac
{
    public class AutofacCodeflowFactory : ICodeflowFactory
    {
        private readonly ILifetimeScope _lifetimeScope;

        public AutofacCodeflowFactory(ILifetimeScope lifetimeScope)
        {
            _lifetimeScope = lifetimeScope;
        }

        public DisposableContext<Codeflow> CreateCodeflow(Type codeflowType)
        {
            var childScope = _lifetimeScope.BeginLifetimeScope();
            var codeFlow = (Codeflow) childScope.Resolve(codeflowType);

            return new DisposableContext<Codeflow>(codeFlow, instance => childScope.Dispose());
        }
    }
}